//
//  LocationManager.m
//

#import "LocationManager.h"
#import "ECAuthorizationTools.h"

@interface LocationManager()<CLLocationManagerDelegate>


@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) ECAuthorizationTools *tools;

@property (nonatomic, copy) void (^getLocCoordinate2DComp)(CLLocationCoordinate2D coordinate);

@end

@implementation LocationManager


+ (instancetype)manager {
    static LocationManager *manager;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (void)dealloc {
    [self stopSerialLocation];
}

- (ECAuthorizationTools *)tools{
    if (!_tools) {
        _tools = [[ECAuthorizationTools alloc] init];
    }
    return _tools;
}

-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        [_locationManager setDesiredAccuracy: kCLLocationAccuracyThreeKilometers];
        [_locationManager setPausesLocationUpdatesAutomatically: NO];
        [_locationManager setAllowsBackgroundLocationUpdates: NO];///是否允许后台定位。默认为NO。只在iOS 9.0及之后起作用。
        _locationManager.distanceFilter = 100.0f;
        
        [_locationManager setDelegate: self];
    }
    return _locationManager;
}


/*
 //未做选择:未选允许、拒绝（例如弹出提示框，用户之间退出APP时会发生）
 kCLAuthorizationStatusNotDetermined = 0,
 
 //受限制：未授权，主动现在定位服务，用户无法改变该状态（可能没有否认个人授权）
 kCLAuthorizationStatusRestricted,
 
 // 拒绝:用户拒绝授权，可在设置在修改
 kCLAuthorizationStatusDenied,
 
 //授权且在未使用APP时使用定位
 kCLAuthorizationStatusAuthorizedAlways NS_ENUM_AVAILABLE(NA, 8_0),
 
 // 授权且当APP使用中使用定位
 kCLAuthorizationStatusAuthorizedWhenInUse NS_ENUM_AVAILABLE(NA, 8_0),
 
 // 已废弃：不做解释，在官方demo中也不在关注该值
 kCLAuthorizationStatusAuthorized
 */
//MARK: 是否允许定位
- (void)alloAccessToLocationAtComplete:(void(^)(NSInteger errcode))complete{
    [self.tools checkAndRequestAccessForLocationServicesWithAccessStatus:^(ECLocationAuthorizationStatus status) {
        if (status == ECLocationAuthorizationStatus_Denied
            || status == ECLocationAuthorizationStatus_Restricted||
            status == ECLocationAuthorizationStatus_NotSupport) {//拒绝 或 应用没有相关权限，且当前用户无法改变这个权限，比如:家长控制
            if (complete)  complete(status);

        }else if (status == ECLocationAuthorizationStatus_Authorized
            || status == ECLocationAuthorizationStatus_AuthorizedAlways
            || status == ECLocationAuthorizationStatus_AuthorizedWhenInUse) {//已经授权
            if (complete)  complete(status);
        }
    }];
}

//MARK: 开始定位
- (void)startSerialLocation
{
    [self.locationManager startUpdatingLocation];
    // 单次定位
//    [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
}

//MARK: 停止定位
- (void)stopSerialLocation
{
    if (_locationManager) {
        [_locationManager stopUpdatingLocation];
        _locationManager.delegate = nil;
        _locationManager  = nil;
    }

    if (_tools) {
        _tools = nil;
    }
    
}


//MARK: 定位错误
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self stopSerialLocation];//
    
}

//MARK: 定位结果
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {

    CLLocation *newLocation = [locations firstObject];
    if(self.getLocCoordinate2DComp) {
        self.getLocCoordinate2DComp(newLocation.coordinate);
    }
    self.coordinate = CLLocationCoordinate2DMake(newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    [self stopSerialLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> *placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks) {
            NSLog(@"name,%@", place.name); // 位置名
            NSLog(@"thoroughfare,%@", place.thoroughfare);// 街道
            NSLog(@"subThoroughfare,%@", place.subThoroughfare);// 子街道
            NSLog(@"locality,%@", place.locality); // 市
            NSLog(@"subLocality,%@", place.subLocality); // 区
            NSLog(@"country,%@", place.country);// 国家
            NSLog(@"administrativeArea,%@", place.administrativeArea);// 国家
        }
        CLPlacemark *firPlace = [placemarks firstObject];

        if (self.geocodeLocationComp) {
            self.geocodeLocationComp(firPlace);
        }
        
        
    }];

}

//MARK: 定位权限状态改变时回调函数
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([CLLocationManager locationServicesEnabled]) {
            [self.locationManager startUpdatingLocation];
        }
    });
   
}

- (void)getLocation:(void (^)(CLLocationCoordinate2D coordinate))complection {
    self.getLocCoordinate2DComp = complection;
    kWeakSelf;
    [self alloAccessToLocationAtComplete:^(NSInteger errcode) {
        if (errcode == ECLocationAuthorizationStatus_Denied
            || errcode == ECLocationAuthorizationStatus_Restricted||
            errcode == ECLocationAuthorizationStatus_NotSupport) {//拒绝 或 应用没有相关权限，且当前用户无法改变这个权限，比如:家长控制
            //权限有误，停止定位
            CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(0, 0);
            if (weakSelf.getLocCoordinate2DComp){
                weakSelf.getLocCoordinate2DComp(coordinate);
            }
            [weakSelf stopSerialLocation];
            
        }else if (errcode == ECLocationAuthorizationStatus_Authorized
                  || errcode == ECLocationAuthorizationStatus_AuthorizedAlways
                  || errcode == ECLocationAuthorizationStatus_AuthorizedWhenInUse) {//已经授权
//            [weakSelf startSerialLocation];
        }
    }];
}
@end
